package com.cqupt.scanning.security.config;

import com.cqupt.scanning.security.utils.JwtTokenUtil;
import com.cqupt.scanning.security.utils.ResponseUtil;
import com.cqupt.scanning.system.utils.result.R;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Data: 2021/7/12 10:54
 * @Author: 宋宝梁
 */
public class TokenLogoutHandler implements LogoutHandler {
    private JwtTokenUtil jwtTokenUtil;
    private RedisTemplate redisTemplate;
    private JwtSecurityProperties jwtSecurityProperties;

    public TokenLogoutHandler(JwtTokenUtil jwtTokenUtil,
                              RedisTemplate redisTemplate,
                              JwtSecurityProperties jwtSecurityProperties) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.redisTemplate = redisTemplate;
        this.jwtSecurityProperties = jwtSecurityProperties;

    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String authHeader = request.getHeader(jwtSecurityProperties.getHeader());
        if (authHeader != null && authHeader.startsWith(jwtSecurityProperties.getTokenStartWith())) {
            String token = authHeader.substring(jwtSecurityProperties.getTokenStartWith().length());
            //清空当前用户缓存中的权限数据
            String userName = jwtTokenUtil.parseToken(token);
            Boolean delete = redisTemplate.delete(userName);
            ResponseUtil.out(response, R.ok());
        }
        ResponseUtil.out(response, R.error());
    }
}
